package com.cci.kangdao.task;


import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeJSONArrayEntity;
import com.cci.kangdao.crmapi.CRMServiceApi;
import com.cci.kangdao.dao.CampaignTaskSyncDao;
import com.cci.kangdao.utilTool.CollectionUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.MapStringConvert;
import org.apache.commons.collections4.MapUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


@Component
public class CampaignTaskSchedule {
	private Logger log = Logger.getLogger(this.getClass().getName());
	@Resource
	private CampaignTaskSyncDao campaignTaskSyncDao;
	@Autowired
	private CRMServiceApi crmServiceApi;



	//campaign任务所有的定时重传
    public void campaignTaskSchedule(){
		try {
			log.info("重试campaign任务异常队列-开始");
			List<Map<String,Object>> campaignTaskSyncList = campaignTaskSyncDao.getCampaignTaskSyncList();
			if(CollectionUtils.isNotEmpty(campaignTaskSyncList)){
				for(Map<String,Object> campaignTask : campaignTaskSyncList){
					String channelHost = MapUtils.getString(campaignTask,"ChannelHost","");
					String syncData = MapUtils.getString(campaignTask,"SyncData","");
					//同步crm是否成功
					int isSyncSuccess = 1;
					//失败原因
					String syncFailReason = "";
					try {
						Map<String,Object> sfMap = MapStringConvert.stringToMap(syncData);
						if(channelHost.equals("syncDealerCampaignStatusToSF")){   //目前只有这个接口需要重传
							CRMResponeJSONArrayEntity crmResponse = CRMApiUtils.getCRMServiceApi().syncDealerCampaignStatusToSF(sfMap);
							if(crmResponse.getStatus()!=0) {
								log.error("dbu重试campaign任务异常队列失败，状态："+crmResponse.getStatus()+"，用户信息:"+crmResponse.getMessage());
								isSyncSuccess = 0;
								syncFailReason = crmResponse.getMessage();
							}
						}
					}catch (Exception e) {
						log.error("重试campaign任务异常队列发生异常，异常信息"+e.getMessage(),e);
						if(isSyncSuccess == 1){
							isSyncSuccess = 0;
							syncFailReason = e.getMessage();
						}
					}
					campaignTask.put("updator",-1);
					campaignTask.put("updateTime",LocalTimeUtil.getRealCurrentTime());
					campaignTask.put("syncCount",MapUtils.getIntValue(campaignTask,"SyncCount")+1);
					campaignTask.put("id",MapUtils.getLongValue(campaignTask,"ID"));
					//同步失败
					if(isSyncSuccess == 0){
						campaignTask.put("syncStatus",-1);
						campaignTask.put("failReason",syncFailReason);
					}else{
						campaignTask.put("syncStatus",1);
					}
					campaignTaskSyncDao.update(campaignTask);
				}
			}
			log.info("重试campaign任务异常队列-结束");
		} catch (Exception e) {
			log.error("重试campaign任务异常队列发生异常，异常信息"+e.getMessage(),e);
		}
    }


}
